package com.xindaoapp.happypet.ui;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.DiscCacheAware;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.PostImgData;
import com.xindaoapp.happypet.bean.PostImgData.Img;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.ViewPagerFixed;

/**
 * 
 * 帖子详情--查看大图
 * 
 * @author
 * 
 */
public class PostDetailImgsActivity extends BaseActivity {

    private ViewPagerFixed vViewPager;
    private List<Fragment> fragments;
    private String mTid, mAid, mUrl;
    private TextView tv_count, top_bar_right_textview;
    private ImageView top_bar_left_imageview;
    private String mImgUrl = null;
    private List<Img> mImgs = new ArrayList<PostImgData.Img>();


    @Override
    protected int getContentViewResId() {
        // TODO Auto-generated method stub
        return R.layout.activity_post_detail_imgs;
    }

    @Override
    protected void initViews() {
        // TODO Auto-generated method stub
        super.initViews();
        top_bar_right_textview = (TextView) findViewById(R.id.top_bar_right_textview);
        top_bar_left_imageview = (ImageView) findViewById(R.id.top_bar_left_imageview);
        fragments = new ArrayList<Fragment>();
        mUrl = getIntent().getStringExtra(Constants.KEY_IMAGE_URL);
        mTid = getIntent().getStringExtra(Constants.KEY_POST_TID);
        mAid = getIntent().getStringExtra(Constants.PARAM_PHOTO_POSITION);
        vViewPager = (ViewPagerFixed) findViewById(R.id.viewpager);
        tv_count = (TextView) findViewById(R.id.tv_count);
        top_bar_left_imageview.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();
            }
        });


        top_bar_right_textview.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (mImgUrl != null) {
                    saveToSD(mImgUrl);
                }
            }


        });


    }

    @Override
    protected void onLoadDatas() {
        // TODO Auto-generated method stub
        super.onLoadDatas();
        getData();

    }

    private void getData() {

        HappyPetApplication.get().getMoccaApi().getPostImgData(mTid, new IRequest<PostImgData>() {

            @Override
            public void request(PostImgData t) {

                if (null != t) {
                    onDataArrived(true);
                    if (t.array.size() == 0) {
                        onDataArrivedEmpty();
                    } else {
                        mImgs = t.array;
                        for (int i = 0; i < t.array.size(); i++) {

                            fragments.add(MyImgsFragment.newInstance(t.array.get(i).url));

                        }
                        // HappyPetApplication.mHandler.postDelayed(new Runnable() {
                        //
                        // @Override
                        // public void run() {
                        // // TODO Auto-generated method stub
                        // ImgViewPagerAdapter adapter =
                        // new ImgViewPagerAdapter(getSupportFragmentManager(),
                        // fragments);
                        // vViewPager.setAdapter(adapter);
                        // vViewPager.setOnPageChangeListener(adapter);
                        // if (mPosition != null) {
                        // vViewPager.setCurrentItem(Integer.parseInt(mPosition));
                        // } else if (mUrl != null) {
                        //
                        // }
                        // }
                        // }, 500);

                        ImgViewPagerAdapter adapter =
                                new ImgViewPagerAdapter(getSupportFragmentManager(), fragments);
                        vViewPager.setAdapter(adapter);
                        vViewPager.setOnPageChangeListener(adapter);
                        if (mAid != null) {
                            for (int i = 0; i < t.array.size(); i++) {
                                if (mAid.equals(t.array.get(i).aid)) {
                                    vViewPager.setCurrentItem(i);
                                    break;
                                }
                            }
                        } else if (mUrl != null) {
                            for (int i = 0; i < t.array.size(); i++) {
                                if (mUrl.equals(t.array.get(i).url)) {
                                    vViewPager.setCurrentItem(i);
                                    break;
                                }
                            }
                        }


                    }



                } else {
                    onDataArrived(false);
                }
            }

        });



    }

    public class ImgViewPagerAdapter extends FragmentPagerAdapter implements OnPageChangeListener {
        List<Fragment> fragments;
        View[] tabViews;

        public ImgViewPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
            // this.tabViews = tabViews;
            setTabSelected(0);
        }

        @Override
        public Fragment getItem(int arg0) {
            return fragments.get(arg0);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }



        @Override
        public void onPageScrollStateChanged(int arg0) {}

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {}

        @Override
        public void onPageSelected(int position) {
            setTabSelected(position);
        }

        private void setTabSelected(int position) {
            mImgUrl = mImgs.get(position).url;
            tv_count.setText(position + 1 + "/" + fragments.size());
        }
    }

    private final File file = new File(Environment.getExternalStorageDirectory(), "happypet/image");

    /**
     * 将图片保存到本地 来自 ImageLoader中的缓存图片
     */
    private void saveToSD(String imageurl) {
        // TODO Auto-generated method stub
        final DiscCacheAware discCache = ImageLoader.getInstance().getDiscCache();
        File myCaptureFile = new File(file, System.currentTimeMillis() + ".jpg");
        //
        boolean sdCardExist =
                Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {

            // 如果文件夹不存在
            if (!file.exists()) {
                // 按照指定的路径创建文件夹
                file.mkdirs();
            }
            // 检查图片是否存在
            if (!myCaptureFile.exists()) {
                try {
                    myCaptureFile.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        } else {
            showToast("SD卡未挂载");
            return;
        }
        //

        try {
            BufferedOutputStream bos =
                    new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            File bmp = discCache.get(imageurl);
            FileInputStream in = new FileInputStream(bmp);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }
            bos.flush();
            bos.close();
            in.close();
            Toast.makeText(getApplicationContext(), "图片保存至" + myCaptureFile.getAbsolutePath(),
                    Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            Toast.makeText(getApplicationContext(), "保存失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "保存失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}
